/**
 * ajax请求封装
 * created lxc data:2020-10-09
 */
//引入axios和qs
import axios from 'axios'
import Qs from 'qs'
import store from '../store/index'
import local from '@/utils/local'
import router from '../router'


console.log( process.env.VUE_APP_BASE_API)


//统一请求地址
axios.defaults.baseURL = process.env.VUE_APP_BASE_API
//请求超时 5秒超时
axios.defaults.timeouts = 5000

//默认不显示加载动画
let loading = false

axios.defaults.headers['Content-Type'] = 'application/json'

// 请求拦截器
axios.interceptors.request.use(
  (config) => {
    if (loading) store.commit('showLoading')
    // let token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJsb2dpbklkIjoiNTI5NiIsInRpbWUiOiIxNjE3ODUxMzI4MzMxIiwidXNlcklkIjoiNTAyMSJ9.K3h_0dxxxw09k-8ZPCgWawHR7beBzAoQ0N-jG67mhsI"
    let accessToken = local.getCookie("accessToken");
    let token = accessToken.replace(/\"/g, "");
    if (token) config.headers.accessToken = token
    return config
  },
  (err) => {
    return Promise.reject(err)
  }
)

// 响应拦截器
axios.interceptors.response.use(
  (res) => {
    store.commit('hideLoading')
    if (res.data.msgCode == 401 || res.data.msgCode == 311) {
      // let {height} = store.state.height;
      // console.log(height,'req')
      local.clear()
      // store.commit('setHeight',height)
      router.replace('/')
    }
    if (res.data.code === '200') {
      return res.data
    } else {
      // return Promise.reject(res.data)
      return Promise.resolve(res.data)
    }
  },
  (err) => {
      console.log('错误',err)
    if (!err.response) {
      //无网验证
      this.$message.error("请检查你的网络链接")
    }
    return Promise.reject(err)
  }
)

//暴露
export default {
  get(url, params = {}, isloading = { loading: false }) {
    loading = isloading.loading
    return axios.get(url, { params })
  },
  put(url, params , isloading = { loading: false }) {
    loading = isloading.loading
    return axios.put(url,  params )
  },
  post(url, params = {}, isloading = { loading: false }, opt = { json: true }) {
    loading = isloading.loading
    return axios.post(url, opt.json ? params : Qs.stringify(params))
  },
  //file 上传的文件 format 上传的格式限制
  uploadFile(file, format = []) {
    return new Promise((resolve, reject) => {
      if (format.length && !format.includes(file.type)) {
        reject("上传文件格式错误");
      }
      let formData = new FormData();
      formData.append("file", file);
      axios({
        method: "POST",
        url: "http://hapi.elive.vip/uploadImg",
        data: formData,
        headers: {
          "Content-Type": "multipart/form-data"
        },
      })
        .then((res) => {
          let {code, data} = res;
          if (code === "200") {
            resolve(data);
          } else {
            reject(err);
          }
        })
        .catch((err) => {
          reject(err);
        });
    });
  }
}
